package com.mingqi.enetconnected.launch;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.RequiresApi;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.CardView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.InputType;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.mingqi.enetconnected.R;
import com.mingqi.enetconnected.launch.adapter.AccountChooseAdapter;
import com.mingqi.enetconnected.primary.MainActivity;
import com.mingqi.enetconnected.util.resource.ResourceUtils;
import com.mingqi.enetconnected.view.Dialog.LoginDialog;
import com.netease.nim.uikit.common.util.string.StringUtil;
import com.netease.nim.uikit.support.permission.MPermission;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

public class LoginActivity extends AppCompatActivity {

    @BindView(R.id.et_account)
    EditText mEtAccount;
    @BindView(R.id.iv_account_choose)
    ImageView mIvAccountChoose;
    @BindView(R.id.et_password_set)
    EditText mEtPasswordSet;
    @BindView(R.id.iv_password_show)
    ImageView mIvPasswordShow;
    @BindView(R.id.cb_remember_password)
    CheckBox mCbRememberPassword;
    @BindView(R.id.tv_forget_password)
    TextView mTvForgetPassword;
    @BindView(R.id.btn_login)
    Button mBtnLogin;
    @BindView(R.id.iv_user)
    ImageView mIvUser;
    @BindView(R.id.v_line)
    View mVLine;
    @BindView(R.id.root_view)
    NestedScrollView mRootView;
    private PopupWindow mPopupWindow;
    private String accountStr;
    private String passwordStr;
    private InputMethodManager manager;
    private LoginDialog mLoginDialog;
    private int mSpaceDimen;
    private int mLineDimen;
    private int mItemDimen;
    private int[] mLocation;
    private int[] mLocationSign;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        requestBasicPermission();
        ButterKnife.bind(this);

        initData();
        initClick();
    }
    private final String[] BASIC_PERMISSIONS = new String[]{
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.READ_PHONE_STATE
    };

    private void requestBasicPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (!Settings.System.canWrite(this)) {
                Intent goToSettings = new Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS);
                goToSettings.setData(Uri.parse("package:" + this.getPackageName()));
                startActivity(goToSettings);
            }
            MPermission.with( LoginActivity.this)
                    .setRequestCode(110)
                    .permissions(BASIC_PERMISSIONS)
                    .request();

        }


    }

    private void initClick() {

        mTvForgetPassword.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                startActivity(new Intent(LoginActivity.this,ForgetPasswordActivity.class));
            }
        });

        mIvAccountChoose.setOnClickListener(new View.OnClickListener() {
            @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
            @Override
            public void onClick(View v) {

                // TODO: 2018/8/31 有记录
                if(mPopupWindow == null) {

                    showChooseAccountWindow();
                } else {

                    mPopupWindow.showAtLocation(mVLine, Gravity.NO_GRAVITY,mLocationSign[0] - mSpaceDimen,mLocation[1] - mLineDimen);
                }
            }
        });

        mIvPasswordShow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                controlPasswordShow();
            }
        });

        mBtnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                startLogin();
            }
        });
    }

    private void startLogin() {

        boolean judge = judge();
      //  if(judge) {

            login();

       // }
    }

    private void login() {

        // TODO: 2018/8/22 登录
        Intent intent = new Intent(this, MainActivity.class);
        startActivity(intent);
    }

    private boolean judge() {

        obtainInputData();

        if (TextUtils.isEmpty(accountStr)) {

            mLoginDialog.show();
            mLoginDialog.setHintMessage(ResourceUtils.getString(R.string.account_not_null));
            return false;
        }

        if (TextUtils.isEmpty(passwordStr)) {

            mLoginDialog.show();
            mLoginDialog.setHintMessage(ResourceUtils.getString(R.string.password_not_null));
            return false;
        }

        return true;
    }


    private void obtainInputData() {

        if (mEtAccount.getText() != null) {

            accountStr = mEtAccount.getText().toString();
        }

        if(mEtPasswordSet.getText() != null) {

            passwordStr = mEtPasswordSet.getText().toString();
        }
    }

    private void controlPasswordShow() {

        boolean isSelectedSet = mIvPasswordShow.isSelected();

        if (isSelectedSet) {

            mIvPasswordShow.setSelected(false);
            mEtPasswordSet.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
        } else {

            mIvPasswordShow.setSelected(true);
            mEtPasswordSet.setInputType(InputType.TYPE_CLASS_TEXT);
        }

        obtainInputData();

        if (!StringUtil.isEmpty(passwordStr)) {

            mEtPasswordSet.setSelection(passwordStr.length());
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    private void showChooseAccountWindow() {

        CardView cvRoot = (CardView) getLayoutInflater().inflate(R.layout.window_account_choose,null);
        RecyclerView rvAccounts = cvRoot.findViewById(R.id.rv_accounts);

        rvAccounts.setLayoutManager(new LinearLayoutManager(this));
        final List<String> strings = new ArrayList<>();
        for (int i = 0; i < 5; i++) {
            strings.add("12313131313==" + i);
        }

        AccountChooseAdapter adapter = new AccountChooseAdapter(strings);
        rvAccounts.setAdapter(adapter);
        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {

                mEtAccount.setText(strings.get(position));
                mEtAccount.setSelection(strings.get(position).length());
                mPopupWindow.dismiss();
                mPopupWindow = null;
            }
        });

        mSpaceDimen = ResourceUtils.getDimen(R.dimen.x20);
        mLineDimen = ResourceUtils.getDimen(R.dimen.y2);
        mItemDimen = ResourceUtils.getDimen(R.dimen.y50);

        mPopupWindow = new PopupWindow(mIvAccountChoose);
        mPopupWindow.setWidth(mVLine.getWidth() - mSpaceDimen);
        mPopupWindow.setHeight(mItemDimen * 3 + mLineDimen);
        mPopupWindow.setAnimationStyle(R.style.popupWindow_top_scale_show);
        mPopupWindow.setBackgroundDrawable(new BitmapDrawable());
        mPopupWindow.setOutsideTouchable(true);
        mPopupWindow.setFocusable(true);
        mPopupWindow.setContentView(cvRoot);
        mPopupWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        mPopupWindow.showAtLocation(mVLine, Gravity.NO_GRAVITY,mLocationSign[0] - mSpaceDimen,mLocation[1] - mLineDimen);

    }

    private void initData() {

        manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        mLoginDialog = new LoginDialog(this);
        mLoginDialog.setCanceledOnTouchOutside(true);
        mLoginDialog.setCancelable(true);

        Glide.with(this).load(R.drawable.ic_dialog_success)
                .apply(RequestOptions.circleCropTransform()
                .diskCacheStrategy(DiskCacheStrategy.NONE)
                .skipMemoryCache(true)).into(mIvUser);

        mVLine.post(new Runnable() {
            @Override
            public void run() {

                mLocation = new int[2];
                mVLine.getLocationOnScreen(mLocation);
                mLocationSign = new int[2];
                mEtAccount.getLocationOnScreen(mLocationSign);
            }
        });


    }

    /**
     * 视图位置大小确定
     * 缺点：会跟随生命周期多次调用
     * @param hasFocus
     */
    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);

    }

    /**
     * 关闭软键盘
     * @param event
     * @return
     */
    @Override
    public boolean onTouchEvent(MotionEvent event) {

        if (event.getAction() == MotionEvent.ACTION_DOWN) {

            if (getCurrentFocus() != null && getCurrentFocus().getWindowToken() != null) {
                manager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }
        return super.onTouchEvent(event);
    }
}
